<template>
  <div class="outbox">
    <h2>
      家长信息
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
        >添加</el-button
      >
    </h2>

    <el-switch
      v-model="value"
      active-color="#13ce66"
      inactive-color="#ff4949"
      active-text="已登记"
      inactive-text="全部"
    >
    </el-switch>
    <el-table
      :data="
        parentInfo.filter(
          (parent) => !search || parent.parentName.includes(search)
        )
      "
      style="width: 100%"
    >
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="易班昵称" prop="ybUserName"> </el-table-column>

      <el-table-column label="易班id" prop="ybUserId"> </el-table-column>
      <el-table-column label="姓名" prop="parentName"> </el-table-column>
      <el-table-column label="联系方式" prop="parentPhone"> </el-table-column>
      <el-table-column label="邮箱" prop="parentEmail"> </el-table-column>
      <el-table-column label="绑定学生" prop="parentChildName">
      </el-table-column>
      <el-table-column label="绑定学生学号" prop="parentChildId">
      </el-table-column>

      <el-table-column fixed="right" width="150">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入家长/学生的id/姓名搜索"
          />
        </template>
        <template slot-scope="scope">
          <div class="buttons">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="tablePage.pageNum"
        :page-size="tablePage.pageSize"
        :page-sizes="pageSizes"
        :total="tablePage.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div> -->
    <el-dialog
      :title="isAdd ? '添加家长信息' : '修改家长信息'"
      :visible="isDialogVisible"
      @close="isDialogVisible = false"
    >
      <el-form
        :model="formData"
        label-width="100px"
        :rules="formRules"
        ref="formData"
      >
        <el-form-item label="易班昵称" prop="ybUserName">
          <el-input
            v-show="!isAdd"
            v-model="formData.ybUserName"
            disabled
          ></el-input>
          <el-input v-show="isAdd" v-model="formData.ybUserName"></el-input>
        </el-form-item>
        <el-form-item label="易班ID" prop="ybUserId">
          <el-input
            v-show="!isAdd"
            v-model="formData.ybUserId"
            disabled
          ></el-input>
          <el-input v-show="isAdd" v-model="formData.ybUserId"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="parentName">
          <el-input v-model="formData.parentName"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="parentPhone">
          <el-input v-model="formData.parentPhone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="parentEmail">
          <el-input v-model="formData.parentEmail"></el-input>
        </el-form-item>
        <el-form-item label="绑定学生" prop="parentChildName">
          <el-input v-model="formData.parentChildName"></el-input>
        </el-form-item>
        <el-form-item label="绑定学生学号" prop="parentChildId">
          <el-input v-model="formData.parentChildId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">取消</el-button>
        <!-- <el-button v-show="isAdd" type="primary" @click="addParent"
          >添加</el-button
        >
        <el-button v-show="!isAdd" type="primary" @click="changeParent"
          >修改</el-button
        > -->
        <el-button @click="saveEdit" type="primary">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.fetchParentInfo();
  },
  data() {
    return {
      isAdd: true,
      isDialogVisible: false,
      formData: {
        ybUserId: "",
        ybUserName: "",
        parentName: "",
        parentPhone: "",
        parentEmail: "",
        parentChildName: "",
        parentChildId: "",
        parentState: false,
      },
      value: true,
      parentInfo: [
        {
          ybUserId: "",
          ybUserName: "",
          parentName: "",
          parentPhoen: "",
          parentEmail: "",
          parentChildName: "",
          parentChildId: "",
          parentState: false,
        },
      ],
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0, // 总记录数
      },
      pageSizes: [10, 20, 30],
      search: "",
      formRules: {
        ybUserName: [
          { required: true, message: "易班昵称不能为空", trigger: "blur" },
        ],
        ybUserId: [
          { required: true, message: "易班ID不能为空", trigger: "blur" },
        ],
        parentName: [
          { required: false, message: "姓名不能为空", trigger: "blur" },
        ],
        parentPhone: [
          { required: false, message: "联系方式不能为空", trigger: "blur" },
        ],
        parentEmail: [
          { required: false, message: "邮箱不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: ["blur", "change"],
          },
        ],
        parentChildName: [
          { required: false, message: "绑定学生不能为空", trigger: "blur" },
        ],
        parentChildId: [
          { required: false, message: "绑定学生学号不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    value(newVal, oldVal) {
      this.fetchParentInfo();
    },
  },
  methods: {
    saveEdit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 校验通过，执行保存或添加操作
          if (this.isAdd) {
            // 添加
            this.addParent();
          } else {
            // 修改
            this.changeParent();
          }
        } else {
          // 校验不通过，不执行保存或添加操作
          this.$message.error("表单校验不通过，请检查输入！");
        }
      });
    },
    addParent() {
      // 发送添加的请求
      this.$http
        .post(`/parents/add`, this.formData)
        .then((response) => {
          // 处理成功响应，可以刷新列表等操作
          this.$message.success("添加成功");
          this.fetchParentInfo();
          this.isDialogVisible = false; // 关闭添加对话框
          this.formData = {}; //清空数据
        })
        .catch((error) => {
          console.error("Error adding parent:", error);
          this.$message.error("添加失败,该易班id已存在~");
        });
    },
    changeParent() {
      // 发送更新的请求
      this.$http
        .put(`/parents/update`, this.formData)
        .then((response) => {
          // 处理成功响应，可以刷新列表等操作
          this.$message.success("修改成功");
          this.fetchParentInfo();
          this.isDialogVisible = false; // 关闭添加对话框
          this.formData = {}; //清空数据
        })
        .catch((error) => {
          console.error("Error changing parent:", error);
          this.$message("修改失败");
        });
    },

    fetchParentInfo() {
      // 获取家长信息
      this.$http
        .get(`/parents/all`)
        .then((res) => {
          this.value
            ? (this.parentInfo = res.data.filter(
                (parent) => parent.parentState
              ))
            : (this.parentInfo = res.data);
        })
        .catch((error) => {
          console.error("loading parent info error;" + error);
        });
    },
    handleEdit(index, row) {
      this.isAdd = false;
      this.formData = row;
      this.isDialogVisible = true;
    },
    handleAdd() {
      this.isAdd = true;
      this.formData = {};
      this.isDialogVisible = true;
    },
    handleDelete(index, row) {
      let id = row.ybUserId;
      this.$confirm("确定要删除这条记录吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮，调用deleteGrade方法
          this.deleteParent(id);
        })
        .catch(() => {
          // 用户点击了取消按钮，不做任何操作
        });
    },
    deleteParent(id) {
      this.$http
        .delete(`/parents/delete/${id}`)
        .then((response) => {
          // 删除成功后刷新数据
          this.fetchParentInfo();
          this.$message.success("删除成功");
        })
        .catch((error) => {
          console.error("Error deleting parent:", error);
          this.$message.error("删除出错");
        });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      // 在此刷新数据
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      // 在此刷新数据
    },
  },
};
</script>
<style scoped>
.outbox {
  margin: 20px;
}
h2 {
  display: flex;
  justify-content: space-between;
}
.buttons {
  display: flex;
  justify-content: space-between;
}
.pagination {
  margin-top: 30px;
  text-align: center;
}
</style>